local hx__yingyuan = fk.CreateSkill {
  name = "hx__yingyuan",
  tags = { Skill.Compulsory, },
}

hx__yingyuan:addEffect(fk.CardUseFinished, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(hx__yingyuan.name) and player.phase == Player.Play then
      local mark = player:getMark("hx__yingyuan-turn")
      if type(mark) ~= "table" or not table.contains(mark, data.card.trueName) then
        local cardlist = data.card:isVirtual() and data.card.subcards or {data.card.id}
        local room = player.room
        return #cardlist > 0 and table.every(cardlist, function (id)
          return room:getCardArea(id) == Card.Processing
        end)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local chosen = player.room:askToChoosePlayers(player, {
      targets = player.room:getOtherPlayers(player),
      min_num = 1,
      max_num = 1,
      prompt = "#hx__yingyuan-card:::"..data.card:toLogString(),
      skill_name = hx__yingyuan.name,
      cancelable = true
    })
    if #chosen > 0 then
      event:setCostData(self, {tos = chosen[1]})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choices = {"hx__yingyuan-recover", "hx__yingyuan-give"}
    local cards = room:getSubcardsByRule(data.card, { Card.Processing })
    local to = event:getCostData(self).tos
    room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonGive, hx__yingyuan.name, nil, true, player)
    if player:getMark("hx__yingyuan-can") == 0 then
      local choice = room:askToChoice(to, {
        choices = choices,
        skill_name = hx__yingyuan.name,
      })
      room:setPlayerMark(player,"hx__yingyuan-can", 1)
      if choice == "hx__yingyuan-recover" then
        room:recover({
          who = player,
          num = 1,
          skillName = hx__yingyuan.name
        })
        room:changeShield(player, 1)
      else
        local card = room:askToCards(to, {
          min_num = 1,
          max_num = 1,
          include_equip = true,
          skill_name = hx__yingyuan.name,
          cancelable = false,
          pattern = ".",
          prompt = "#hx__yingyuan-give::"..to.id
        })
        if #card > 0 then
          room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonGive, hx__yingyuan.name, nil, true, to)
        end
      end
    end
    if player.dead then return end
    room:addTableMark(player, "hx__yingyuan-turn", data.card.trueName)
  end,
})

hx__yingyuan:addEffect(fk.TurnEnd, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(hx__yingyuan.name) and player:getMark("hx__yingyuan-can") > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"hx__yingyuan-can", 0)
  end,
})

return hx__yingyuan